package util;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;

import static util.TokenHelper.SING;

@Slf4j
@WebFilter(filterName = "JWTFilter"
        ,urlPatterns = "/*")
public class JWTFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp
            , FilterChain chain) throws ServletException, IOException {
        // 1.强制转换
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //2.操作
        String token = request.getHeader("token");
        if (token!=null){
            JSONObject message = new JSONObject();
            Collection<String> collections = new LinkedList<>();
            response.setContentType("application/json;charset=UTF-8");
            //验证过程
            try {
                //创建验证对象
                DecodedJWT verify =
                        JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
                //解码对象
                int size = verify.getClaims().size();
                for (int i = 1; i < size; i++) {
                    collections.add(verify.getClaim(i+"").asString());
                }
                message.put("登陆成功",collections);
            }catch (Exception e){
                message.put("message", "没有权限");
                response.getWriter().println(message);
            }
            response.getWriter().println(message);
        }


        //3.放行
        //执行其他过滤器，若过滤器已执行完毕则执行原求
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
